package com.cby.ssm.controller;

import com.cby.ssm.entity.PermissionEntity;
import com.cby.ssm.service.PermissionService;
import com.cby.ssm.service.Role_PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by 13296 on 2017/7/20.
 */
@Controller
public class PermissionHandler {
    @Autowired
    PermissionService pfun;
    @Autowired
    Role_PermissionService rpfun;

    @ModelAttribute
    public String permissionUtil() {
        return null;
    }

    @RequestMapping(method = RequestMethod.GET, path = "/showPermissions.do")
    public String showPermissionsView(Model model, HttpServletRequest request) {
        List<PermissionEntity> permissionList = null;
        try {
            permissionList = pfun.searchAllPermission();
            model.addAttribute("allPermissions", permissionList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(method = RequestMethod.POST, path = "/showPermissions.do")
    public String showPermissions(HttpServletRequest request) {
        return null;
    }

    @RequestMapping(method = RequestMethod.POST, path = "/addPermission.do")
    public String addPermission(Model model, HttpServletRequest request) {
        return null;
    }

    @RequestMapping(method = RequestMethod.POST, path = "/allocatePermissions.do")
    public String allcatePermissions(String roleId, HttpServletRequest request) {
        try {
            rpfun.deletePermissionsOfRoleId(roleId);
            String[] values = request.getParameterValues("checkPermission");
            for(int i=0;i<values.length;i++){
                System.out.println("permissionId:"+values[i]);
                rpfun.addPermissionOfRoleId(roleId,values[i]);
            }
        } catch (NullPointerException e) {
            System.out.println("没有被选中的！");
            return "redirect:/showRoles.do";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/showRoles.do";
    }

}
